﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using BLL;
using DTO;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using System.Collections;
namespace CRM.GUI.QLKhachHang
{
    public partial class ucManual : UserControl
    {
        private List<CallAgentEntity> _loadCA;
        private List<DTO.RegionEntity> _loadMien;
        private List<DTO.RegionEntity> _loadTinhThanh;
        private List<CallAgentEntity> listCA;
        private List<vw_DWorking> tasklist;
        private List<CustomerEntity> listCustomerForDivide;
        private int CurrentCASelected;

        public ucManual()
        {
            InitializeComponent();
            IntialConfig();
            IntialLoad();
        }

        private void IntialConfig()
        {
            grddskhphanchiamu.BestFitColumns();
            grddskhphanchiamu.OptionsView.ColumnAutoWidth = false;
            grddskhphanchiamu.ScrollStyle = ScrollStyleFlags.LiveHorzScroll | ScrollStyleFlags.LiveVertScroll;
            grddskhphanchiamu.HorzScrollVisibility = ScrollVisibility.Always;
            grddskhphanchiamu.OptionsSelection.MultiSelect = true;
            grddskhphanchiamu.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            griddscallcuaca.BestFitColumns();
            griddscallcuaca.OptionsView.ColumnAutoWidth = false;
            griddscallcuaca.ScrollStyle = ScrollStyleFlags.LiveHorzScroll | ScrollStyleFlags.LiveVertScroll;
            griddscallcuaca.HorzScrollVisibility = ScrollVisibility.Always;
            griddscallcuaca.OptionsSelection.MultiSelect = true;
            griddscallcuaca.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            grdcolCount.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
            grddskhphanchiamu.CustomUnboundColumnData += grddskhphanchiamu_CustomUnboundColumnData;
            grdcolCounter2.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
            griddscallcuaca.CustomUnboundColumnData += griddscallcuaca_CustomUnboundColumnData;
        }

        private void IntialLoad()
        {
            cmbCollectorMa.Properties.DisplayMember = "Collector_Code";
            cmbCollectorMa.Properties.ValueMember = "Collector_ID";
            gridMainMa.UseEmbeddedNavigator = true;
            grdCATask.UseEmbeddedNavigator = true;
            colCurrentBrandName1.DataSource = SharedData.BrandList;
            colCurrentBrandName1.DisplayMember = "Brand_Code";
            colCurrentBrandName1.ValueMember = "Brand_ID";
            colCurrentBrandName2.DataSource = SharedData.BrandList;
            colCurrentBrandName2.DisplayMember = "Brand_Code";
            colCurrentBrandName2.ValueMember = "Brand_ID";
            colCallType1.DataSource = SharedData.CallStatusList;
            colCallType1.DisplayMember = "CallStatusName";
            colCallType1.ValueMember = "CallStatus_ID";
            colCalltype2.DataSource = SharedData.CallStatusList;
            colCalltype2.DisplayMember = "CallStatusName";
            colCalltype2.ValueMember = "CallStatus_ID";

            _loadMien = SharedData.RegionList.Where(a => a.RegionLevel == 1).ToList();
            _loadTinhThanh = SharedData.RegionList.Where(a => a.RegionLevel == 2).ToList();            
            cmbdspkMienMu.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 1).ToList();
            cmbdspkMienMu.DisplayMember = "RegionName";
            cmbdspkMienMu.ValueMember = "Region_Code";
            LoadCAFunc func = new LoadCAFunc();
            _loadCA = func.LoadTotalCallByAllCA();
        }

        private void grddskhphanchiamu_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
                e.Value = e.ListSourceRowIndex + 1;
        }

        private void griddscallcuaca_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
                e.Value = e.ListSourceRowIndex + 1;
        }

        private void checkCAManualData()
        {
            if (cbxCAName2.EditValue.ToString() != "default")
            {
                LoadCAFunc func = new LoadCAFunc();
                CurrentCASelected = (int)cbxCAName2.EditValue;
                if (CurrentCASelected > 0)
                {
                    List<CustomerEntity> list = func.LoadCurrentCallByCAId(CurrentCASelected);
                    if (list != null)
                    {
                        grdCATask.DataSource = list;
                    }
                }
                checkManualData();
            }
            else
            {
                btnAllToRightMu.Enabled = false;
                btnEachToRightMu.Enabled = false;
            }
        }

        private void checkManualData()
        {
            if (grddskhphanchiamu.DataRowCount > 0 && cbxCAName2.EditValue != null)
            {
                btnEachToRightMu.Enabled = true;
                btnAllToRightMu.Enabled = true;
            }
            else
            {
                btnEachToRightMu.Enabled = false;
                btnAllToRightMu.Enabled = false;
               // gridMainMa.DataSource = null;
                
            }
            if (griddscallcuaca.DataRowCount > 0)
            {
                btnEachToLeftMu.Enabled = true;
                btnAllToLeftMu.Enabled = true;
            }
            else
            {
                btnEachToLeftMu.Enabled = false;
                btnAllToLeftMu.Enabled = false;
                grdCATask.DataSource = null;
            }
        }

        int CARegion;
        private void cmbdspkMienMu_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (int.TryParse(cmbdspkMienMu.SelectedValue.ToString(), out CARegion))
            {
                cbxCAName2.Enabled = true;
                cbxCAName2.Properties.DataSource = _loadCA.Where(a => a.RegionCode == CARegion).ToList();
            }
            else
            {
                cbxCAName2.Enabled = false;
            }
        }


        private void cbxCAName2_EditValueChanged(object sender, EventArgs e)
        {
            checkCAManualData();
        }

        private void cmbPeriod_EditValueChanged(object sender, EventArgs e)
        {
            FilterListByCallStatus();
        }

        private void btnEachToRightMu_Click(object sender, EventArgs e)
        {
            if (grddskhphanchiamu.DataRowCount > 0 && CurrentCASelected > 0)
            {
                int[] d = grddskhphanchiamu.GetSelectedRows();
                List<long> customers = new List<long>();
                LoadCAFunc func = new LoadCAFunc();
                foreach (int i in d)
                {
                    if (i != -1 && CurrentCASelected > 0)
                    {
                        CustomerEntity ce = (CustomerEntity)grddskhphanchiamu.GetRow(i);
                        customers.Add(ce.Customer_ID);
                    }
                }
                grddskhphanchiamu.DeleteSelectedRows();
                func.AssignCallsToCA(customers, CurrentCASelected);
                grdCATask.DataSource = func.LoadCurrentCallByCAId(CurrentCASelected);
                RefreshUI();
                checkManualData();
            }
            else
            {
                MessageBox.Show("Không tìm thấy danh sách khách hàng hoặc chưa chọn Call Agent!");
            }
        }

        private void btnAllToRightMu_Click(object sender, EventArgs e)
        {
            LoadCAFunc func = new LoadCAFunc();
            if (gridMainMa.DataSource != null && CurrentCASelected > 0)
            {
                List<long> customers = new List<long>();
                foreach (CustomerEntity i in gridMainMa.DataSource as List<CustomerEntity>)
                {
                    if (i != null && CurrentCASelected > 0)
                    {
                        customers.Add(i.Customer_ID);
                    }
                }
                func.AssignCallsToCA(customers, CurrentCASelected);
                grdCATask.DataSource = func.LoadCurrentCallByCAId(CurrentCASelected);
                RefreshUI();
                checkManualData();

                for (int  rowIndex = 0;rowIndex < grddskhphanchiamu.RowCount;rowIndex++)
                {
                    grddskhphanchiamu.DeleteRow(rowIndex);
                }
               // gridMainMa.DataSource = null;
            }
            else
            {
                MessageBox.Show("Không tìm thấy danh sách khách hàng hoặc chưa chọn Call Agent!");
            }
        }

        private void btnEachToLeftMu_Click(object sender, EventArgs e)
        {
            if (gridMainMa.DataSource != null)
            {
                LoadCAFunc func = new LoadCAFunc();
                int[] d = griddscallcuaca.GetSelectedRows();
                List<long> customers = new List<long>();
                foreach (int i in d)
                {
                    if (i != -1 && CurrentCASelected > 0)
                    {
                        CustomerEntity ce = (CustomerEntity)griddscallcuaca.GetRow(i);
                        customers.Add(ce.Customer_ID);
                    }
                }
                func.RemoveCallsByCAId(customers, CurrentCASelected);
                grdCATask.DataSource = func.LoadCurrentCallByCAId(CurrentCASelected);
                RefreshUI();
                checkManualData();
            }
        }

        private void btnAllToLeftMu_Click(object sender, EventArgs e)
        {
            LoadCAFunc func = new LoadCAFunc();
            if (cmbSourceMa.EditValue == null)
            {
                MessageBox.Show("Chưa chọn nguồn", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                List<long> customers = new List<long>();                
                for (int i = 0; i < griddscallcuaca.RowCount; i++)
                {
                    int rowHandle = griddscallcuaca.GetVisibleRowHandle(i);
                    if (griddscallcuaca.IsDataRow(rowHandle))
                    {
                        customers.Add(((CustomerEntity)griddscallcuaca.GetRow(rowHandle)).Customer_ID);
                    }
                }

                func.RemoveCallsByCAId(customers, CurrentCASelected);
            }
            grdCATask.DataSource = func.LoadCurrentCallByCAId(CurrentCASelected);
            RefreshUI();
            checkManualData();
        }
        private bool IsSourceHasValue()
        {
            int sourceid;
            if (int.TryParse(cmbSourceMa.EditValue.ToString(), out sourceid) || sourceid > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void cmbSource_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (IsSourceHasValue())
            {
                LoadCAFunc func = new LoadCAFunc();
                tasklist = func.CountDWList((int)cmbSourceMa.EditValue);
                cmbCollectorMa.Properties.DataSource = tasklist;
            }

        }

        private void cmbCallType_EditValueChanged(object sender, EventArgs e)
        {
            //Show EDDS in combobox

            if (listCustomerForDivide != null)
            {
                if (!string.IsNullOrEmpty(cmbCallTypeMa.EditValue.ToString()))
                {
                    var listCallType = cmbCallTypeMa.EditValue.ToString().Split(',');
                
                    ArrayList listEDDS = new ArrayList();
                    ArrayList listEDDStmp = new ArrayList();
                    foreach (var item in listCallType)
                    {
                        var listtmp = (from list in listCustomerForDivide.Where(a => a.CallStatus == int.Parse(item))
                                       group list by list.EDDS into g
                                       select new
                                       {
                                           EDDS = g.FirstOrDefault().EDDS,
                                       });
                        foreach (var edds in listtmp)
                        {
                            listEDDS.Add(edds);
                        }
                    }
                    cmbPeriodMa.Properties.DataSource = listEDDS.ToArray().Distinct();
                    cmbPeriodMa.Properties.DisplayMember = "EDDS";
                    cmbPeriodMa.Properties.ValueMember = "EDDS";
                    cmbPeriodMa.CheckAll();
                }
                else
                {
                    cmbPeriodMa.SetEditValue(null);
                    cmbPeriodMa.Properties.DataSource = null;
                }
            }
             FilterListByCallStatus();
        }

        private void cmbCollector_EditValueChanged(object sender, EventArgs e)
        {
            cmbCallTypeMa.Properties.Items.Clear();
            cmbPeriodMa.Properties.Items.Clear();
            gridMainMa.DataSource = null;
            if (cmbSourceMa.EditValue != null && cmbCollectorMa.EditValue != null)
            {
                LoadCAFunc func = new LoadCAFunc();
                listCustomerForDivide = func.LoadCustomerForDivide((int)cmbSourceMa.EditValue, (int)cmbCollectorMa.EditValue);

                //Show CallStatus in Combobox
                cmbCallTypeMa.Properties.DataSource = from a in listCustomerForDivide.Where(a => a.Collector_ID == (int)cmbCollectorMa.EditValue)
                                                      group a by a.CallStatus into g
                                                    select new
                                                    {
                                                        CallStatus = g.FirstOrDefault().CallStatus,
                                                        CallStatusName = SharedData.CallStatusList.Where(a => a.CallStatus_ID == g.FirstOrDefault().CallStatus).SingleOrDefault().CallStatusName,
                                                    };
                cmbCallTypeMa.Properties.DisplayMember = "CallStatusName";
                cmbCallTypeMa.Properties.ValueMember = "CallStatus";
                listCA = func.LoadTotalCallByAllCA();
                cmbPeriodMa.CheckAll();
                cmbCallTypeMa.CheckAll();
                checkManualData();               
            }

        }

        private void dtpStartDate_ValueChanged(object sender, EventArgs e)
        {
            LoadSource();
        }

        private void dtpEndDate_ValueChanged(object sender, EventArgs e)
        {
            LoadSource();
        }

        private void LoadSource()
        {
            cmbSourceMa.Properties.DataSource = null;
            LoadSourceFunc func = new LoadSourceFunc();
            cmbSourceMa.Properties.DisplayMember = "SourceName";
            cmbSourceMa.Properties.ValueMember = "Source_ID";
            cmbSourceMa.Properties.DataSource = func.LoadSourceForDivide(dtpStartDate.Value, dtpEndDate.Value);
            cmbSourceMa.Text = "Chọn Nguồn";
        }

        private void FilterListByCallStatus()
        {
            if (cmbSourceMa.EditValue != null && cmbCollectorMa.EditValue != null)
            {
                if (!string.IsNullOrWhiteSpace(cmbCallTypeMa.EditValue.ToString()))
                {
                    LoadCAFunc func = new LoadCAFunc();
                    listCustomerForDivide = func.LoadCustomerForDivide((int)cmbSourceMa.EditValue, (int)cmbCollectorMa.EditValue);
                    var list = new List<CustomerEntity>();
                    foreach (string callstatus in cmbCallTypeMa.EditValue.ToString().Split(','))
                    {
                        var listtmp = listCustomerForDivide.Where(a => a.CallStatus == int.Parse(callstatus.Trim())).ToList();
                        foreach (string edds in cmbPeriodMa.EditValue.ToString().Split(','))
                        {
                            var listtmpedds = listtmp.Where(a => a.EDDS == edds.Trim()).ToList();
                            foreach (var cus in listtmpedds)
                            {
                                list.Add(cus);
                            }
                        }
                        
                    }
                    gridMainMa.DataSource = list;
                }
                else
                {
                    gridMainMa.DataSource = null;

                }
            }
        }

        private void RefreshUI()
        {
            LoadCAFunc func = new LoadCAFunc();
            _loadCA = func.LoadTotalCallByAllCA();
            cbxCAName2.Properties.DataSource = _loadCA.Where(a => a.RegionCode == CARegion).ToList();
            if (IsSourceHasValue())
            {
                tasklist = func.CountDWList((int)cmbSourceMa.EditValue);
                cmbCollectorMa.Properties.DataSource = tasklist;
            }
            FilterListByCallStatus();
        }
    }
}
